package com.fieldchain.ex.fa100.utils.net.modle;

import com.fieldchain.ex.fa100.bean.event.BaseEvent;
import com.fieldchain.ex.fa100.utils.net.inter.BaseRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/4
 */
public abstract class StringListRequest extends BaseRequest {
    private int code = 0;
    private String msg;

    @Override
    public void baseOnSucess(String jsonstr, String tags) {
        try {
            JSONObject jsonRoot = new JSONObject(jsonstr);
            code = jsonRoot.getInt("code");
            msg = jsonRoot.getString("msg");
            EventBus.getDefault().post(new BaseEvent(code, tags));
            if (code == 200) {
                List<String>    list = new Gson().fromJson(jsonRoot.getString("data"), new TypeToken<List<String>>() {}.getType());
                onSucess(list, code, msg);
            } else {
                onSucess(new ArrayList<String>(), code, msg);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void baseOnFaild(Exception e, String tags) {
        EventBus.getDefault().post(new BaseEvent(code, tags));
        onFaild(e);
    }

    public abstract void onSucess(List<String> list, int code, String msg);

    public abstract void onFaild(Exception e);
}
